Attach = require('../models/attach').Attach
dataPage = require('../services/dataPage').queryPage
resErr = require('./util').resErr
util = require("util")
common_util = require('../services/common_util')
file_util = require('../services/file_util')

exports.attach_add = (req,res) ->
  if !req.param('file_id')
    return resErr(res,"请先上传文件再保存！")
  if !common_util.trim(req.param("file_name"))
    return resErr(res,"附件名称不能为空！")
  attach = new Attach
  attach.add req,(err)->
    if err
      resErr(res,err)
    else
      res.json({'flag':'success'})



exports.attach_list = (req,res) ->
  params = {}
  #相当于sql里面like的写法
  params.category = req.param("category")  unless !req.param("category")
  sorts = {order:1,update_at:-1}
  dataPage Attach,params,sorts,req.param("pageSize") or req.param("limit"),req.param("pageNum") or req.param("page"), (err,results) ->
    if err
      resErr(res,err)
    else
      res.json(results)


exports.attach_del = (req,res) ->
  _id = req.param('_id')
  if !_id
    resErr(res,'编码不得为空')
  else
    Attach.findById _id, (err,doc) ->
      if err
        return resErr res,err
      gridfs_id = doc.file_id
      Attach.findByIdAndRemove _id,(err)->
        if err
          resErr res,err
        else
          file_util.delete_by_file_id gridfs_id,(err) ->
            if err
              return resErr res,err
            res.json({'success':true})


exports.attach_detail = (req,res) ->
  _id = req.param('_id')
  if !_id
    resErr(res,'编码不得为空')
  else
    Attach.findById _id, (err,result) ->
      if err
        resErr(res,err)
      else
        res.json(result)


exports.attach_edit = (req,res) ->
  _id = req.param('_id')
  if !_id
    return resErr res,"编码不得为空！"
  if !common_util.trim(req.param("file_name"))
    return resErr(res,"附件名称不能为空！")
  params = {}
  params.category = req.param('category')
  params.file_id = req.param('file_id')
  params.file_name = req.param('file_name')
  params.file_desc = req.param('file_desc')
  params.file_size = req.param("file_size")
  params.order = req.param("order")
  params.updated_at = new Date

  Attach.findByIdAndUpdate _id,params,(err) ->
    if err
      resErr(res,err)
    else
      res.json({'success':'true'})